package org.ala.tiktools.rpc.kcp.client_server;

import org.ala.tiktools.logs.LoggerFactory;
import org.ala.tiktools.rpc.client_server.service.impls.AbstractRpcServiceReceiver;
import org.ala.tiktools.rpc.kcp.config.RpcKcpConfigInfo;
import org.ala.tiktools.rpc.kcp.netty.server.KcpServerChannel;
import org.ala.tiktools.rpc.netty.handler.RpcChannelInitializer;
import org.slf4j.Logger;
import org.springframework.context.ApplicationContext;

import io.netty.channel.Channel;

/**
 *
 *	@author ala
 *	@date 2025年4月20日
 */
public class KcpReceiver extends AbstractRpcServiceReceiver  {

	
	static Logger log = LoggerFactory.getLogger("rpc", "init");
	
	
	/**
	 * 	主channel组，自己维护
	 */
	protected KcpServerChannel[] mainChannels;
	
	
	@Override
	public Channel init(ApplicationContext applicationContext) {
        //  启动netty服务端（boss线程数 == ports数）
        int[] ports = RpcKcpConfigInfo.INSTANCE.getPorts();
        mainChannels = KcpNettyTools.bind(ports, new RpcChannelInitializer(getExecutor(), false, true, this::channelRegistered, this::channelUnRegistered));
        for (KcpServerChannel mainChannel : mainChannels) {
        	log.info("[KcpReceiver init] Kcp服务端开启 channel:{}", mainChannel);
        }
        return null;
	}


	@Override
	public void destroy() throws Exception {
		if (mainChannels == null) {return;}
		for (Channel channel : mainChannels) {
			log.info("[KcpNodeReceiver init] netty服务端销毁 local:{}", channel.localAddress());
			channel.close().sync();
		}
	}

}
